/**
 * 操作日志模块 - 日志数据生成器
 * @description 生成客户档案管理相关的操作日志数据
 * @author CRM开发团队
 * @version 1.0.0
 */

import Mock from 'mockjs'
import { generateChineseName } from '@/mock/data/customer-data'
import type { OperationLog } from '@/api/customer'

// ==========================================
// 操作日志常量数据
// ==========================================

// 操作类型
export const OPERATION_TYPES = ['CREATE', 'UPDATE', 'DELETE', 'VIEW'] as const

// 表名称
export const TABLE_NAMES = [
  'customers',
  'customer_tags', 
  'travel_preferences',
  'health_info',
  'family_info'
] as const

// 字段名称映射
export const FIELD_NAMES = {
  customers: [
    'customer_name', 'customer_status', 'primary_phone', 'gender', 
    'birth_date', 'id_card', 'address', 'work_status', 'occupation'
  ],
  customer_tags: ['tag_name', 'tag_category', 'is_system'],
  travel_preferences: [
    'budget_range', 'payment_preference', 'domestic_regions', 
    'landscape_preferences', 'transport_preferences'
  ],
  health_info: [
    'health_status', 'mobility_ability', 'chronic_diseases',
    'medication_info', 'dietary_restrictions'
  ],
  family_info: [
    'marital_status', 'spouse_info', 'children_info', 
    'decision_pattern', 'influence_factors'
  ]
} as const

// 操作员角色
export const USER_ROLES = [
  '销售顾问', '客服专员', '系统管理员', '数据分析师', '市场专员'
] as const

// 变更原因
export const CHANGE_REASONS = [
  '客户信息更新',
  '客户主动要求修改',
  '系统数据维护',
  '数据准确性修正',
  '业务流程调整',
  '合规性要求',
  '客户状态变更',
  '定期数据审核',
  '客户投诉处理',
  '系统升级迁移'
] as const

// ==========================================
// 日志数据生成器
// ==========================================

/**
 * 生成单条操作日志
 */
export function generateOperationLog(customerId: number, options?: {
  operationType?: typeof OPERATION_TYPES[number]
  tableName?: typeof TABLE_NAMES[number]
  userId?: number
  timeOffset?: number // 时间偏移（天数）
}): OperationLog {
  const operationType = options?.operationType || Mock.Random.pick(OPERATION_TYPES)
  const tableName = options?.tableName || Mock.Random.pick(TABLE_NAMES)
  const fieldName = Mock.Random.pick(FIELD_NAMES[tableName])
  const userId = options?.userId || Mock.Random.integer(1, 100)
  
  // 计算创建时间
  const timeOffset = options?.timeOffset || Mock.Random.integer(0, 90)
  const createdAt = new Date(Date.now() - timeOffset * 24 * 60 * 60 * 1000)
  
  // 根据操作类型生成不同的值
  let oldValue = ''
  let newValue = ''
  
  switch (operationType) {
    case 'CREATE':
      oldValue = ''
      newValue = generateFieldValue(fieldName, tableName)
      break
    case 'UPDATE':
      oldValue = generateFieldValue(fieldName, tableName)
      newValue = generateFieldValue(fieldName, tableName)
      break
    case 'DELETE':
      oldValue = generateFieldValue(fieldName, tableName)
      newValue = ''
      break
    case 'VIEW':
      oldValue = ''
      newValue = ''
      break
  }

  return {
    id: Mock.Random.increment(),
    customerId,
    tableName,
    operationType,
    fieldName: operationType === 'VIEW' ? undefined : fieldName,
    oldValue: operationType === 'VIEW' ? undefined : oldValue,
    newValue: operationType === 'VIEW' ? undefined : newValue,
    changeReason: operationType === 'VIEW' ? undefined : Mock.Random.pick(CHANGE_REASONS),
    ipAddress: Mock.Random.ip(),
    createdAt: createdAt.toISOString(),
    createdBy: {
      id: userId,
      name: generateChineseName().fullName,
      role: Mock.Random.pick(USER_ROLES)
    }
  }
}

/**
 * 根据字段名生成合适的字段值
 */
function generateFieldValue(fieldName: string, tableName: string): string {
  switch (fieldName) {
    // 客户基础信息字段
    case 'customer_name':
      return generateChineseName().fullName
    case 'customer_status':
      return Mock.Random.pick(['有效客户', '潜在客户', '无效客户', '已成交客户'])
    case 'primary_phone':
      return Mock.Random.pick(['138', '139', '137']) + Mock.Random.string('number', 8)
    case 'gender':
      return Mock.Random.pick(['男', '女'])
    case 'birth_date':
      return Mock.Random.date('yyyy-MM-dd')
    case 'address':
      return Mock.Random.city() + Mock.Random.county() + Mock.Random.cword(5, 10)
    case 'work_status':
      return Mock.Random.pick(['在职', '退休', '待业', '其他'])
    case 'occupation':
      return Mock.Random.pick(['工程师', '教师', '医生', '公务员', '企业管理'])
    
    // 标签字段
    case 'tag_name':
      return Mock.Random.pick(['VIP客户', '优质客户', '价格敏感客户', '易沟通', '需要关怀'])
    case 'tag_category':
      return Mock.Random.pick(['价值分类', '服务特点', '出行特点', '健康状态', '消费习惯'])
    case 'is_system':
      return Mock.Random.boolean().toString()
    
    // 旅游偏好字段
    case 'budget_range':
      return Mock.Random.pick(['经济型', '舒适型', '品质型', '豪华型'])
    case 'payment_preference':
      return Mock.Random.pick(['现金支付', '银行转账', '微信支付', '支付宝'])
    case 'domestic_regions':
      return Mock.Random.pick(['华北', '华东', '华南', '西南'])
    case 'landscape_preferences':
      return Mock.Random.pick(['自然风光', '历史古迹', '海滨度假', '温泉养生'])
    case 'transport_preferences':
      return Mock.Random.pick(['飞机', '高铁', '普通火车', '大巴车'])
    
    // 健康信息字段
    case 'health_status':
      return Mock.Random.pick(['健康良好', '健康一般', '健康较差', '健康很差'])
    case 'mobility_ability':
      return Mock.Random.pick(['行动自如', '轻微受限', '需要辅助', '轮椅出行'])
    case 'chronic_diseases':
      return Mock.Random.pick(['高血压', '糖尿病', '关节炎', '无'])
    case 'medication_info':
      return Mock.Random.pick(['降压药', '降糖药', '止痛药', '无'])
    case 'dietary_restrictions':
      return Mock.Random.pick(['无特殊要求', '低盐低脂', '糖尿病餐', '素食'])
    
    // 家庭信息字段
    case 'marital_status':
      return Mock.Random.pick(['已婚', '丧偶', '离异', '未婚'])
    case 'spouse_info':
      return generateChineseName().fullName
    case 'children_info':
      return `${Mock.Random.integer(0, 3)}个子女`
    case 'decision_pattern':
      return Mock.Random.pick(['自主决策', '咨询决策', '共同决策', '代为决策'])
    case 'influence_factors':
      return Mock.Random.pick(['价格因素', '安全因素', '健康因素', '家人意见'])
    
    default:
      return Mock.Random.cword(3, 8)
  }
}

/**
 * 为客户生成完整的操作日志历史
 */
export function generateCustomerOperationLogs(
  customerId: number, 
  count: number = 20,
  options?: {
    startDays?: number // 开始时间（多少天前）
    endDays?: number   // 结束时间（多少天前）
  }
): OperationLog[] {
  const logs: OperationLog[] = []
  const startDays = options?.startDays || 90
  const endDays = options?.endDays || 0
  
  for (let i = 0; i < count; i++) {
    const timeOffset = Mock.Random.integer(endDays, startDays)
    const log = generateOperationLog(customerId, { timeOffset })
    logs.push(log)
  }
  
  // 按时间倒序排列（最新的在前）
  return logs.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
}

/**
 * 生成特定操作类型的日志
 */
export function generateSpecificOperationLog(
  customerId: number,
  operationType: typeof OPERATION_TYPES[number],
  tableName: typeof TABLE_NAMES[number],
  fieldName: string,
  oldValue: string = '',
  newValue: string = '',
  changeReason: string = ''
): OperationLog {
  return {
    id: Mock.Random.increment(),
    customerId,
    tableName,
    operationType,
    fieldName: operationType === 'VIEW' ? undefined : fieldName,
    oldValue: operationType === 'VIEW' ? undefined : oldValue,
    newValue: operationType === 'VIEW' ? undefined : newValue,
    changeReason: operationType === 'VIEW' ? undefined : (changeReason || Mock.Random.pick(CHANGE_REASONS)),
    ipAddress: Mock.Random.ip(),
    createdAt: new Date().toISOString(),
    createdBy: {
      id: Mock.Random.integer(1, 100),
      name: generateChineseName().fullName,
      role: Mock.Random.pick(USER_ROLES)
    }
  }
}

/**
 * 生成系统日志（自动化操作）
 */
export function generateSystemOperationLog(
  customerId: number,
  operationType: typeof OPERATION_TYPES[number],
  description: string
): OperationLog {
  return {
    id: Mock.Random.increment(),
    customerId,
    tableName: 'customers',
    operationType,
    fieldName: undefined,
    oldValue: undefined,
    newValue: undefined,
    changeReason: description,
    ipAddress: '127.0.0.1',
    createdAt: new Date().toISOString(),
    createdBy: {
      id: 0,
      name: '系统',
      role: '系统管理员'
    }
  }
}